﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI.XWPF.UserModel;
using System.IO;
using System.Globalization;

namespace ProjectStudy
{
    public partial class Word导出 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ToWord(this.div1,"自动生成的word_");
        }
        
        //将table导出为word
        public void ToWord(System.Web.UI.Control controlId,string fileName)
        {
            string time = DateTime.Now.ToString("yyyyMMddHHmmss", new CultureInfo("zh-CHS"));

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "";

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="+fileName+time+".doc");
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //更改ContentType的值为ms-word即可实现导出到Word   
            HttpContext.Current.Response.ContentType = "application/ms-word";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword   
            controlId.Page.EnableViewState = false;
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            controlId.RenderControl(hw);
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }
    }
}